package com.kun.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证鉴权工具
 *
 * @author kun.li
 */
@Slf4j
public class SecurityUtil {

    // 扩展密码模式
    public static final String PASSWORD_GRANT = "urn:ietf:params:oauth:grant-type:password_code";


    public static void accessDeniedException(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException accessDeniedException) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter writer = response.getWriter();
            Map<String, Object> responseResult = new HashMap<>();
            responseResult.put("code", 403);
            responseResult.put("message", accessDeniedException.getMessage());
            writer.write(objectMapper.writeValueAsString(responseResult));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @SneakyThrows
    public static void authDeniedException(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException authException) {
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        PrintWriter writer = response.getWriter();
        Map<String, Object> responseResult = new HashMap<>();
        responseResult.put("code", 401);
        String message = "";
        if (authException instanceof InvalidBearerTokenException) {
            message = "jwt 解码失败";
        }
        responseResult.put("message", message);
        writer.write(objectMapper.writeValueAsString(responseResult));
        writer.flush();
        writer.close();
    }
}
